package com.eqdd.yiqidian.ui.gongneng.renshi.zuzhiguanli;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.ZuzhijiagouShowActivityCustom;
import com.eqdd.yiqidian.adapter.MyFragmentPagerAdapter;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.SectionArcBean;
import com.eqdd.yiqidian.bean.rebuild.DepartmentListResultBean;
import com.eqdd.yiqidian.fragment.renshi.BumenListFragment;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.ui.base.TapActivity;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.EditDialogFragment;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

public class ZuzhijiagouShowActivity extends TapActivity {
    private ZuzhijiagouShowActivityCustom dataBinding;
    private MyFragmentPagerAdapter myFragmentPagerAdapter;
    private List<String> title = new ArrayList<>();
    private List<Fragment> views = new ArrayList<>();
    private List<String> ids = new ArrayList<>();
    private ActionSheetDialog bottomChoose;
    private EditDialogFragment editDiglog;
    private DepartmentListResultBean departmentListResultBean;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        super.onCreate(savedInstanceState);
    }
    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_zuzhijiagou_show);
        initTopTitleBar(View.VISIBLE, "组织管理");
        initTopRightText("添加", (v) -> {
            bottomChoose.show();
        });
    }

    @Override
    public void initData() {

        myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), title, views);
        dataBinding.viewPager.setAdapter(myFragmentPagerAdapter);
        dataBinding.slidingTabStrip.setViewPager(dataBinding.viewPager);

    }

    @Override
    public void setView() {
        initChooseDialog();
        DepartmentListResultBean departmentListResultBean = new DepartmentListResultBean();
        departmentListResultBean.setCompanyId(user.getCompanyId() + "");
        departmentListResultBean.setDepartId("0");
        departmentListResultBean.setParentId("0");
        departmentListResultBean.setDepartName(user.getCompany());
        addFragment(departmentListResultBean);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {


        }
    }

    public void addFragment(DepartmentListResultBean departmentListResultBean) {
        this.departmentListResultBean = departmentListResultBean;
        for (int i = 0; i < ids.size(); i++) {
            if (departmentListResultBean.getParentId().equals(ids.get(i))) {
                int len = ids.size();
                for (int j = len - 1; j >= i + 1; j--) {
                    title.remove(j);
                    views.remove(j);
                    ids.remove(j);
                }
                break;
            }
        }
        if (departmentListResultBean.getDepartId().equals("0")) {
            title.add(departmentListResultBean.getDepartName());
        }else {
            title.add("->"+departmentListResultBean.getDepartName());

        }

        BumenListFragment fragment = new BumenListFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(Config.DEPARTMENT, departmentListResultBean);
        fragment.setArguments(bundle);
        views.add(fragment);
        ids.add(departmentListResultBean.getDepartId() + "");
        myFragmentPagerAdapter.notifyDataSetChanged();
        dataBinding.viewPager.setCurrentItem(views.size() - 1);
    }

    public void removeFragment(SectionArcBean sectionArcBean) {
        for (int i = 0; i < ids.size(); i++) {
            if ((sectionArcBean.getId() + "").equals(ids.get(i))) {

            }
        }
        title.add(sectionArcBean.getDname());
        BumenListFragment fragment = new BumenListFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("bumen", sectionArcBean);
        fragment.setArguments(bundle);
        views.add(fragment);
        myFragmentPagerAdapter.notifyDataSetChanged();
        dataBinding.viewPager.setCurrentItem(views.size() - 1);
    }

    private void initChooseDialog() {
        bottomChoose = ChooseAlertView.getBottomChoose(this, null, new String[]{"新增部门", "新增职位"}, (v, p) -> {
            switch (p) {
                case 1:
                    editDiglog = ChooseAlertView.getEditDiglog(title.get(dataBinding.viewPager.getCurrentItem()), "请输入部门名称（例如：人事部）", "请输入部门编码（例如：HR）", (content) -> {
                        if (TextUtils.isEmpty(content.get(0)) || TextUtils.isEmpty(content.get(1))) {
                            ToastUtil.showLong("信息不完整，添加失败");
                            return;
                        }
                        createDepartment(content);
                    });
                    editDiglog.show(getSupportFragmentManager(), "edit");
                    break;
                case 2:
                    Bundle bundle = new Bundle();
                    SectionArcBean sectionArcBean = new SectionArcBean();
                    sectionArcBean.setId(ids.get(dataBinding.viewPager.getCurrentItem()));
                    sectionArcBean.setDname(title.get(dataBinding.viewPager.getCurrentItem()));
                    bundle.putParcelable(Config.DEPARTMENT, departmentListResultBean);
                    startActivityForResult(AddCareerActivity.class, bundle, Config.ADD_CAREER);
                    break;
            }
        });
        ChooseAlertView.getBottomChoose(this, null, new String[]{"新增部门"}, (v, p) -> {
            switch (p) {
                case 1:
                    editDiglog = ChooseAlertView.getEditDiglog(title.get(dataBinding.viewPager.getCurrentItem()), "请输入部门名称（例如：人事部）", "请输入部门编码（例如：HR）", (content) -> {
                        if (TextUtils.isEmpty(content.get(0)) || TextUtils.isEmpty(content.get(1))) {
                            ToastUtil.showLong("信息不完整，添加失败");
                            return;
                        }
                        createDepartment(content);
                    });
                    editDiglog.show(getSupportFragmentManager(), "edit");
                    break;
            }
        });
    }

    private void createDepartment(List<String> content) {
        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.CREATE_SECTION)
                .params("companyId", user.getCompanyId())
                .params("parentId", ids.get(dataBinding.viewPager.getCurrentItem()))
                .params("name", content.get(0))
                .params("userGuid", user.getGuid())
                .params("desc", content.get(1))
                .execute(new DialogCallBack<HttpResult>(this) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            Fragment item = myFragmentPagerAdapter.getItem(dataBinding.viewPager.getCurrentItem());
                            ((BumenListFragment) item).refresh();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.ADD_CAREER:
                    Fragment item = myFragmentPagerAdapter.getItem(dataBinding.viewPager.getCurrentItem());
                    ((BumenListFragment) item).refresh();
                    break;
            }
        }
    }
}
